<template>
	<view>
		<view class="msg_wrap">
			<view class="nick">
					<text>昵称:</text>
					<u-input placeholder="输入昵称" v-model="nickname"></u-input>
			</view>
			
			<view class="msg_list">
				
				<view :class="item.isMe=='true'?'msg_me':'other'" v-for="item in msgList">
					 <text>{{item.msg}}</text>
					 <text>:{{item.nickname}}</text>
				</view>
			</view>
			<view class="msg_footer">
				<view>
					<u-input v-model="msg"  placeholder="输入问题"></u-input>
				</view>
				<view>
					<u-button type="success" @click="sendMsg">发送</u-button>
				</view>
			</view>
		</view>
		
	</view>
</template>

<script>
	// webscoket  全双工通信协议    长连接
	// 协议以ws
	// 它在一个TCP连接上持续通信，减少了连接和断开的次数
	// webscoket 不存在跨域问题
	
	
	// http 协议  https协议
	// 首先由后端提供websocket接口
	
	
		 
	export default {
		data(){
			return {
				wsc:"",
				nickname:"", //昵称
				msg:"",//消息
				msgList:[]//消息列表
			}
		},
		onLoad(){
			//  1. 建立websocket连接new WebSocket(连接地址)
			this.wsc=new WebSocket("ws://192.168.110.35:3000")
			//2监听websocket.onopen监听连接成功 
			this.wsc.onopen=function(){
				console.log("连接成功")
				
			}
			// 3.监听后台返回数据的onmessage ！！！！！
			let that=this;
			this.wsc.onmessage=function(res){
				console.log(res);
				// res.data 返回的数据
				// console.log(JSON.parse(res.data))
				// 
				let data=JSON.parse(res.data)
				if(data.type=="msg"){
					console.log(data)
					that.msgList.push(data)
				}
				console.log(that.msgList)
			}
			
			// 4.onclose 监听连接断开的
			this.wsc.onclose=function(){
				console.log("连接断开")
			}
			
			// 5.onerror  监听连接错误
			this.wsc.onerror=function(){
				console.log("监听连接错误")
			}
		
			
		},
		methods:{
			sendMsg(){
				//6 点击发送给websocket后台数据ws.send()  !!!!
				this.wsc.send(
						JSON.stringify({
							nickname:this.nickname,
							msg:this.msg
						})
				)
				// 7 ws.close方法 断开连接
				// this.wsc.close();
				
				
			}
		}
	}
</script>

<style lang="scss">
	.msg_wrap{
		width: 100vw;
		.nick{
			width: 300px;
			margin: 20px 0;
			display: flex;
			align-items: center;
		}
		.msg_list{
			
			.msg_me{
				height: 50px;
				border: 1px solid black;
				background: green;
				padding: 0 10px;
				line-height: 50px;
				float: right;
				>view{
					margin-left: 10px;
				}
			}
			.other{
				height: 50px;
				border: 1px solid black;
				background: white;
				padding: 0 10px;
				margin-left: 10px;
				line-height: 50px;
				float: left;
				>view{
					margin-left: 10px;
				}
			}
		}
		.msg_footer{
			width: 100%;
			display: flex;
			align-items: center;
			position: fixed;
			bottom:0;
			left:0;
			background: white;
			z-index:999;
			>view:nth-child(1){
				flex:1;
			}
			>view:nth-child(2){
				width:200px;
			}
		}
	}
</style>